package oop.ex2.expression;

import oop.ex2.exceptions.EmptyExpression;
import oop.ex2.exceptions.ExpectedAtomicExpression;
import oop.ex2.exceptions.ExpectedBinaryOperation;
import oop.ex2.exceptions.TerminatingStringNotFound;
import oop.ex2.exceptions.TokenNotRecognized;
import oop.ex2.exceptions.UnrecognizedVariable;
import oop.ex2.tokenizer.Tokenizer;

/**
 * This implements a node which stores a variable. It holds a reference to a variable
 * table that it uses in order to return a value.
 * @author daniel_i_l
 *
 */
public class VariableNode extends ExpressionNode {
	private final static NodeType NODE_TYPE = NodeType.ATOM;
	private VariableTable _variableTable;
	
	/**
	 * Construct a variable node using the matched string and a variable table.
	 * @param matchedString The string that was matched that caused this node to be generated.
	 * @param variableTable The variable table that should be used to evaluate a variable.
	 */
	public VariableNode(String matchedString, VariableTable variableTable) {
		super(matchedString);
		_nodeType = NODE_TYPE;
		_variableTable = variableTable;
	}

	@Override
	public void generateChildren(Tokenizer tokenizer)
			throws TokenNotRecognized, EmptyExpression,
			ExpectedAtomicExpression, ExpectedBinaryOperation,
			TerminatingStringNotFound {
		
		//has no children so return
		return;

	}

	@Override
	public double calculateNode() throws UnrecognizedVariable {
		if (_variableTable.hasVariable(_matchedString))
			return _variableTable.getValue(_matchedString);
		
		throw new UnrecognizedVariable("The variable " + _matchedString + " is unrecognized");
			
	}

}
